import React from 'react';
import {Button, Checkbox, Flex, Form, Space, message,InputNumber} from "antd";
import type {CheckboxOptionType} from 'antd/es/checkbox/Group';
import Input from "antd/es/input/Input";
import {
    PlusOutlined,
    SearchOutlined,
    CloseCircleOutlined,
    CheckCircleOutlined,
    CheckOutlined,
    SyncOutlined,
} from '@ant-design/icons';
import {useEffect, useState} from 'react';
import {fileIsOnline, saveConfigData, configPageData} from '../../api/FileSynConfigAPI'


const ConfigIndex: React.FC = () => {
    const [form] = Form.useForm();
    const [messageApi, contextHolder] = message.useMessage();
    const [pageInitData, setPageInitData] = useState({
        onlineLoad: false,
        onlineStatus: null,
    });

    const [formData, setFormData] = useState({
        id: '',
        ip: '',
        port: '',
        localPath: '',
        model: '',
        realTimeStatus:[],
        timingStr: '',
    })
// 模拟 componentDidMount
    useEffect(() => {
        console.log('componentDidMount');

        initData()
    },[]);

    const updateData = (updatedInfo) => {
        setPageInitData({
            ...pageInitData,
            ...updatedInfo
        });
    };
    const LoadIsOnline = () => {
        //手动触发校验
        let validateFields = form.validateFields(['ip', 'port']);
        validateFields.then(res => {
            let formFieldsValue = form.getFieldsValue();
            serverIsOnLine(formFieldsValue)
        }).catch(() => {
        })


    }

    const plainOptions = [
        {label: '实时同步', value: '实时同步', disable: true},
        {label: '定时同步', value: '定时同步', disable: true},
    ];
    const checkBoxChange = (checkedValues: CheckboxOptionType[]) => {
        console.log('checked = ', checkedValues);
    }

    const serverIsOnLine = (params) => {
        updateData({onlineLoad: true, onlineStatus: null})
        fileIsOnline(params).then(res => {
            if (res.code == 200 && res.data == 'true') {
                updateData({onlineLoad: false, onlineStatus: true})
            } else updateData({onlineLoad: false, onlineStatus: false})
        })


    }
    //保存表单数据
    const saveFormData = () => {
        //校验参数
        console.log()
        form.validateFields().then(formParams => {
            console.log(formParams)
            saveConfigData(formParams).then((res) => {
                console.log(res)
                let data = res.data;
                form.setFieldValue("id", data.id)
                messageApi.open({
                    type: 'success',
                    content: '操作成功',
                });
            })
        })
    }
    //初始化页面数据
    const initData = () => {

        configPageData().then(res => {
            let data = res.data;
            console.log(data)
            form.setFieldsValue(data)
            setFormData({
                ...formData,
                ...data
            })
        })
    }

    return (
        <div>
            <Form
                form={form}
                name="basic"
                labelCol={{span: 4}}
                wrapperCol={{span: 6}}
                layout="horizontal">
                <Form.Item noStyle name="id"><Input
                    placeholder="id" style={{display: 'none'}}/></Form.Item>
                <Form.Item label="同步服务器：">
                    <Space.Compact>
                        <Form.Item noStyle rules={[{required: true, message: 'Please input ip!'}]} name="ip"><Input
                            placeholder="请输入IP" name="ip" style={{width: 120}}/></Form.Item>
                        <Form.Item noStyle rules={[{required: true, message: 'Please input port!'}]} name="port"><Input
                            placeholder="port" name="port" style={{width: 70}}/></Form.Item>
                    </Space.Compact>
                    {
                        pageInitData.onlineStatus == null ?
                            <SyncOutlined spin={pageInitData.onlineLoad} onClick={LoadIsOnline}
                                          style={{marginLeft: 10, color: '#08c'}}/>
                            :
                            <>
                                {pageInitData.onlineStatus == true ?
                                    <CheckCircleOutlined spin={pageInitData.onlineLoad} onClick={LoadIsOnline}
                                                         style={{marginLeft: 10, color: '#05ea3b'}}/> :
                                    <CloseCircleOutlined spin={pageInitData.onlineLoad} onClick={LoadIsOnline}
                                                         style={{marginLeft: 10, color: '#ec0b0b'}}/>
                                }
                            </>
                    }
                </Form.Item>
                <Form.Item label="本地同步路径：" name="localPath" rules={[{required: true, message: '请输入磁盘路径'}]}>
                    <Input placeholder="请输入磁盘路径"/>
                </Form.Item>
                <Form.Item label="下载速度（kb/s）：" name="maxRate">
                    <InputNumber placeholder="请输入下载速度"/>
                </Form.Item>
                <Form.Item label="文件同步最大重试次数：" name="maxRetryCount">
                    <InputNumber placeholder="请输入" min="0" max="10" />
                </Form.Item>
                <Form.Item label="过滤文件：" name="filterFormat">
                    <Input.TextArea placeholder="请输入文件后缀名"/>
                </Form.Item>
                <Form.Item label="同步模式：" name="realTimeStatus"  >
                    <Checkbox.Group  options={plainOptions} defaultValue={formData.realTimeStatus} onChange={checkBoxChange}/>
                </Form.Item>
                <Form.Item label="定时配置：">
                    <Form.Item noStyle name="timingStr"><Input
                        placeholder="请输入定时表达式"/></Form.Item>
                    <Button type="dashed" block icon={<PlusOutlined/>}>
                        添加
                    </Button>
                </Form.Item>
                <Form.Item wrapperCol={{offset: 6, span: 16}}>
                    <Button type="primary" onClick={saveFormData}>
                        保存
                    </Button>
                </Form.Item>
            </Form>
            {contextHolder}
        </div>
    )
}
export default ConfigIndex
